<?php

namespace App\Jobs;

use App\Models\Download;
use App\Services\ObsService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Http\UploadedFile;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class DownloadsJob implements ShouldQueue
{
    use Dispatchable;
    use InteractsWithQueue;
    use Queueable;
    use SerializesModels;

    public $download;

    /**
     * Create a new job instance.
     *
     * @param mixed $data
     */
    public function __construct(Download $download)
    {
        $this->download = $download;
    }

    /**
     * Execute the job.
     */
    public function handle()
    {
        set_time_limit(0);

        Excel::store(new $this->download->model($this->download), 'public/' . $this->download->name, 'local');
        $file = new UploadedFile(storage_path('app/public/' . $this->download->name), $this->download->name);
        $path = (new ObsService())->upload('downloads/' . $this->download->agent_id . '/' . explode('.', $this->download->name)[0], $file);

        if ($path) {
            $this->download->update(['status' => 1, 'url' => $path, 'upload_status' => 1]);
            Storage::disk('local')->delete('public/' . $this->download->name);
        } else {
            $this->download->update(['upload_status' => 0]);
            Storage::disk('local')->delete('public/' . $this->download->name);
        }

        return 1;
    }
}
